<template>
  <div class="live-classroom">
    <!-- 顶部导航栏 -->
    <LiveHeader :roomInfo="roomInfo" />

    <!-- 提醒条 -->
    <ReminderBar :time="startTime" :onlineCount="onlineCount" />

    <div class="content-wrapper">
      <!-- 主要内容区 -->
      <div class="main-content">
        <!-- 讲师/主画面 -->
        <MainStream :roomInfo="roomInfo" ref="mainStream" />

        <!-- 右侧面板 -->
        <div class="right-panel">
          <!-- 参会者列表 -->
          <ParticipantsList :students="students" />
          <!-- 聊天区域 -->
          <ChatSection :messages="messages" @send="sendMessage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted, provide, unref } from "vue";
import { ElMessage } from "element-plus";
import LANWebRTCConnection from "@/utils/LANWebRTCConnection.js";
import WebRTCConnection from "@/utils/WebRTCConnection.js";
import LiveHeader from "@/components/live/LiveHeader.vue";
import ReminderBar from "@/components/live/ReminderBar.vue";
import MainStream from "@/components/live/MainStream.vue";
import ParticipantsList from "@/components/live/ParticipantsList.vue";
import ChatSection from "@/components/live/ChatSection.vue";

const messageContainer = ref(null);
const newMessage = ref("");

// 生成随机头像的函数
const getRandomAvatar = (seed) => {
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}`;
};

// 房间信息
const roomInfo = ref({
  id: "room123",
  title: "高级JavaScript编程实战课程",
  teacherName: "张老师",
  teacherAvatar: getRandomAvatar("teacher"),
});

// 在线人数
const onlineCount = ref(42);
const mainStream = ref(null);
const localStram = ref(null);
const peerCon = ref(null);

// 学生列表
const students = ref([
  {
    id: 1,
    name: "学生1",
    audioEnabled: false,
    videoEnabled: true,
    avatar: getRandomAvatar("student1"),
    hasCamera: true,
    hasMicrophone: true,
    isSpeaking: false,
  },
  {
    id: 2,
    name: "学生2",
    audioEnabled: false,
    videoEnabled: false,
    avatar: getRandomAvatar("student2"),
    hasCamera: true,
    hasMicrophone: true,
  },
  {
    id: 3,
    name: "学生3",
    audioEnabled: false,
    videoEnabled: false,
    avatar: getRandomAvatar("student3"),
    hasCamera: false,
    hasMicrophone: true,
  },
]);

// 聊天消息
const messages = ref([
  {
    id: 1,
    sender: "学生1",
    content: "老师，这个知识点能再讲详细一点吗？",
    avatar: getRandomAvatar("student1"),
  },
  {
    id: 2,
    sender: "张老师",
    content: "好的，我再详细讲解一下这部分内容",
    avatar: roomInfo.value.teacherAvatar,
  },
]);

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim()) {
    messages.value.push({
      id: Date.now(),
      sender: "我",
      content: newMessage.value,
      avatar: roomInfo.value.teacherAvatar, // 使用老师的头像
    });
    newMessage.value = "";
    // 滚动到最新消息
    setTimeout(() => {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }, 0);
  }
};

// 添加开始时间
const startTime = ref("8:00 AM");

// 模拟学生说话的函数（实际项目中应该根据音量检测来触发）
const simulateSpeaking = (studentId) => {
  const student = students.value.find((s) => s.id === studentId);
  if (student && student.audioEnabled) {
    student.isSpeaking = true;
    setTimeout(() => {
      student.isSpeaking = false;
    }, 2000); // 模拟说话持续2秒
  }
};

// 开始直播、录屏
const startLive = () => {
  // TODO: 开始直播、录屏
  console.log("开始直播、录屏");
  return new Promise((resolve) => {
    // 共享屏幕
    const screenShare = async () => {
      try {
        // 检查浏览器是否支持屏幕共享
        if (
          !navigator.mediaDevices ||
          !navigator.mediaDevices.getDisplayMedia
        ) {
          throw new Error("您的浏览器不支持屏幕共享功能");
        }

        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: {
            cursor: "always",
            displaySurface: "monitor", // 'monitor', 'window', 'application', 'browser'
          },
          audio: true,
        });
        localStram.value = stream;
        const videoTracks = stream.getVideoTracks();
        if (videoTracks.length > 0) {
          console.log(`Sharing screen with id: ${videoTracks[0].id}`);
        }
        mainStream.value.setVideoStream(stream);
        peerCon.value.startAddChunk(stream);
      } catch (error) {
        console.error("Error sharing screen:", error);
      }
    };
    resolve(screenShare());
  });
};

// 结束直播、录屏
const endLive = () => {
  // TODO: 结束直播、录屏
  console.log("end live");
  localStram.value.getTracks().forEach((track) => {
    track.stop();
  });
  mainStream.value.setVideoStream(null);
  localStram.value = null;
  peerCon.value && peerCon.value.close();
  peerCon.value = null;
};

onMounted(() => {
  peerCon.value = new LANWebRTCConnection();
});

onUnmounted(() => {});

provide("START_LIVE", startLive);
provide("END_LIVE", endLive);
</script>

<style lang="scss" scoped>
.live-classroom {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #0a0b1a;
  color: #fff;

  .content-wrapper {
    flex: 1;
    display: flex;
    overflow: hidden;

    .main-content {
      flex: 1;
      display: flex;
      height: calc(100vh - 108px);

      .right-panel {
        width: 300px;
        background: #1e1f3a;
        border-left: 1px solid rgba(255, 255, 255, 0.1);
        display: flex;
        flex-direction: column;
        height: 100%;
      }
    }
  }
}

.control-btn {
  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;

    &:hover {
      background: none;
      color: #999;
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.context-menu {
  position: fixed;
  background: #2b2b2b;
  border-radius: 8px;
  min-width: 200px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  z-index: 1000;

  .menu-title {
    padding: 8px 16px;
    font-size: 14px;
    color: #fff;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  }

  .menu-items {
    padding: 4px 0;
  }

  .menu-item {
    padding: 8px 16px;
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    color: #fff;
    transition: all 0.3s;

    &:hover {
      background: rgba(255, 255, 255, 0.1);
    }

    &.disabled {
      opacity: 0.5;
      cursor: not-allowed;

      &:hover {
        background: none;
      }
    }
  }
}

@keyframes volume-wave {
  0%,
  100% {
    transform: scaleY(0.5);
  }
  50% {
    transform: scaleY(1);
  }
}

.el-icon {
  font-size: 16px;
  vertical-align: middle;
}

.control-btn {
  .el-icon {
    font-size: 18px;
  }

  &.active .el-icon {
    color: #4080ff;
  }
}

.mic-status {
  .el-icon {
    font-size: 14px;
    color: #4080ff;
  }

  &.mic-off .el-icon {
    color: #ff4d4f;
  }
}
</style>
